/*
  This file is part of Open-Doors.

  Open-Doors is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  Open-Doors is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with Open-Doors.  If not, see <http://www.gnu.org/licenses/>.

  Authors: Rune Thorbek & Araz B. Makoo
*/ 

var indsamler_win;

function renderTip(val, meta, rec, rowIndex, colIndex, store) {
    meta.tdAttr = 'data-qtip="' + val.replace(new RegExp('\ ', 'g'), "&nbsp") + '"';
    return val;
}

function showIndsamlerForm(title, edit, data) {
    if (!indsamler_win) {
        var form = Ext.widget('form', {
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            border: false,
            bodyPadding: 10,
	    
            fieldDefaults: {
                labelAlign: 'top',
                labelWidth: 100,
                labelStyle: 'font-weight:bold',
		labelSeparator: "" 
            },
                defaults: {
                    margins: '0 0 0 0'
                },
	    
            items: [{
		xtype: 'textfield',
		id: 'form_indsamler_edit',
                fieldLabel: 'edit',
		hidden: true
	    }, {
                xtype: 'textfield',
		id: 'form_indsamler_uid',
                fieldLabel: 'uid',
		hidden: true
	    },{
                xtype: 'textfield',
		id: 'form_indsamler_indsamlernummer',
                fieldLabel: 'Indsamlernummer',
		disabled: true
	    }, {
                xtype: 'textfield',
		id: 'form_indsamler_fornavn',
                fieldLabel: 'Fornavn*',
		allowBlank: false
	    }, {
                xtype: 'textfield',
		id: 'form_indsamler_efternavn',
                fieldLabel: 'Efternavn*',
		allowBlank: false
	    }, {
                xtype: 'textfield',
		id: 'form_indsamler_mobiltelefon',
                fieldLabel: 'Mobiltelefon*'
	    }, {
                xtype: 'textfield',
		id: 'form_indsamler_fastnettelefon',
                fieldLabel: 'Fastnettelefon'
	    }, {
                xtype: 'textfield',
		    id: 'form_indsamler_emailadresse',
                fieldLabel: 'Emailadresse',
                vtype: 'email',
	    }, {
                xtype: 'textareafield',
		id: 'form_indsamler_adresse',
                fieldLabel: 'Adresse*',
                labelAlign: 'top',
		allowBlank: false,
                flex: 1,
                margins: '0',
	    }, {
		xtype: 'container',
	
		layout: 'hbox',
		border: false,
		items: [{
		    xtype: 'combobox',
		    id: 'form_indsamlere_group',
		    width: 253,
		    fieldLabel: 'Indsamlingsgruppe',
		    displayField: 'name',
		    valueField: 'uid',
		    labelWidth: 130,
		    store: 'GruppeCombobox',
		    queryParam: 'search_value',
		    queryMode: 'remote',
		    queryDelay: 20,
		    minChars: 0,
		    triggerAction: 'query'
		}, {
		    xtype: 'button',
		    width: 100,
		    text: 'Gå til',
		    handler: function() {
			var o = Ext.getCmp('form_indsamlere_group');
			if (o.getValue() != '') {
			    var index = o.getStore().findExact("uid", o.getValue());
			    var data = o.getStore().getAt(index);
			    if (data != null) {
				if (this.up('form').getForm().isValid()) {
				    commit_indsamler();
				    
				    showGruppeForm('Rediger gruppe', true, data);
				    this.up('form').getForm().reset();
				    this.up('window').hide();
				}
			    }
			}
		    },
		    margin: "18 0 0 10"
		}]
	    }, {
		xtype: 'container',
	
		layout: 'hbox',
		border: false,
		items: [{
		    xtype: 'combobox',
		    id: 'form_indsamlere_campaign',
		    width: 253,
		    fieldLabel: 'Kampagne',
		    displayField: 'name',
		    valueField: 'uid',
		    labelWidth: 130,
		    store: 'KampagneCombobox',
		    queryParam: 'search_value',
		    queryMode: 'remote',
		    queryDelay: 20,
		    minChars: 0,
		    triggerAction: 'query'
		}, {
		    xtype: 'button',
		    width: 100,
		    text: 'Gå til',
		    handler: function() {
			var o = Ext.getCmp('form_indsamlere_campaign');
			if (o.getValue() != '') {
			    var index = o.getStore().findExact("uid", o.getValue());
			    var data = o.getStore().getAt(index);
			    if (data != null) {
				if (this.up('form').getForm().isValid()) {
				    commit_indsamler();
				
				    showKampagneForm('Rediger kampagne', true, data);
				    this.up('form').getForm().reset();
				    this.up('window').hide();
				}
			    }
			}
		    },
		    margin: "18 0 0 10"
		}]
	    }, {
		xtype: 'container',
	
		layout: 'hbox',
		border: false,
		items: [{
		    xtype: 'combobox',
		    id: 'form_indsamlere_venue',
		    width: 253,
		    fieldLabel: 'Mødested*',
		    displayField: 'name',
		    valueField: 'uid',
		    labelWidth: 130,
		    store: 'VenueCombobox',
		    queryParam: 'search_value',
		    queryMode: 'remote',
		    queryDelay: 20,
		    minChars: 0,
		    triggerAction: 'query',
		    allowBlank: false
		}, {
		    xtype: 'button',
		    width: 100,
		    text: 'Gå til',
		    handler: function() {
			var o = Ext.getCmp('form_indsamlere_venue');
			if (o.getValue() != '') {
			    var index = o.getStore().findExact("uid", o.getValue());
			    var data = o.getStore().getAt(index);
			    if (data != null) {
				if (this.up('form').getForm().isValid()) {
				    commit_indsamler();
				    
				    showVenueForm('Rediger mødested', true, data);
				    this.up('form').getForm().reset();
				    this.up('window').hide();
				}
			    }
			}
		    },
		    margin: "18 0 0 10"
		}]
	    }],
	    
	    buttons: [{
                text: 'Ok',
                handler: function() {
                    if (this.up('form').getForm().isValid()) {
			if (Ext.getCmp('form_indsamler_mobiltelefon').getValue() == '' &&
			    Ext.getCmp('form_indsamler_fastnettelefon').getValue() == '' ) {
			    Ext.MessageBox.alert("Fejl", "Der skal angives enten et mobil- eller fastnettelefonnummmer.");
			    return;
			}
			
			commit_indsamler();
                        this.up('form').getForm().reset();
                        this.up('window').hide();
		    }
                }
            }, {
                text: 'Annuller',
                handler: function() {
                    this.up('form').getForm().reset();
                    this.up('window').hide();
                }
		
	    }]
        });
	
        indsamler_win = Ext.widget('window', {
            title: title,
            closeAction: 'hide',
            width: 400,
            height: 560,
            layout: 'fit',
            resizable: false,
            modal: true,
            items: form
        });
    }

    indsamler_win.down('form').getForm().reset();
    if (edit) {
	if (data.get('venue_uid') != 0 && data.get('venue_uid') != null) {
	    var store = Ext.getCmp('form_indsamlere_venue').getStore();
	    store.clearFilter(true);
	    //store.removeAll(true);
	    store.filter([
		{property: "uid_value", value: data.get('venue_uid')}
		//{property: "search_value", value: data.get('venue_name')}
	    ]);
	    //store.load();
	    store.clearFilter(true);
	    Ext.getCmp('form_indsamlere_venue').setValue(parseInt(data.get('venue_uid')));
	}
	if (data.get('group_uid') != 0 && data.get('group_uid') != null) {
	    var store = Ext.getCmp('form_indsamlere_group').getStore();
	    store.clearFilter(true);
	    store.filter([
		{property: "uid_value", value: data.get('group_uid')}
		//{property: "search_value", value: data.get('group_name')}
	    ]);
	    //store.load();
	    store.clearFilter(true);
	    Ext.getCmp('form_indsamlere_group').setValue(parseInt(data.get('group_uid')));
	}
	if (data.get('campaign_uid') != 0 && data.get('campaign_uid') != null) {
	    var store = Ext.getCmp('form_indsamlere_campaign').getStore()
	    store.clearFilter(true);
	    store.filter([
		{property: "uid_value", value: data.get('campaign_uid')}
		//{property: "search_value", value: data.get('campaign_name')}
	    ]);
	    //store.load();
	    store.clearFilter(true);
	    Ext.getCmp('form_indsamlere_campaign').setValue(parseInt(data.get('campaign_uid')));
	}


	Ext.getCmp('form_indsamler_edit').setValue(edit);
	Ext.getCmp('form_indsamler_uid').setValue(data.get('uid'));
	Ext.getCmp('form_indsamler_indsamlernummer').setValue(data.get('number'));
	Ext.getCmp('form_indsamler_fornavn').setValue(data.get('first_name'));
	Ext.getCmp('form_indsamler_efternavn').setValue(data.get('last_name'));
	Ext.getCmp('form_indsamler_mobiltelefon').setValue(data.get('mobile_number'));
	Ext.getCmp('form_indsamler_fastnettelefon').setValue(data.get('phone_number'));
	Ext.getCmp('form_indsamler_emailadresse').setValue(data.get('email_address'));
	Ext.getCmp('form_indsamler_adresse').setValue(data.get('address'));
	//Ext.getCmp('form_indsamler_indsamlernummer').enable();
    } else {
	
	Ext.getCmp('form_indsamler_indsamlernummer').setValue("Nyoprettet");
	//Ext.getCmp('form_indsamler_indsamlernummer').disable();
    }

    indsamler_win.setTitle(title);
    indsamler_win.show();
}


function commit_indsamler() {
  
    var edit_value = Ext.getCmp('form_indsamler_edit').getValue();
    var uid_value = Ext.getCmp('form_indsamler_uid').getValue();
    var number_value = Ext.getCmp('form_indsamler_indsamlernummer').getValue();
    var first_name_value = Ext.getCmp('form_indsamler_fornavn').getValue();
    var last_name_value = Ext.getCmp('form_indsamler_efternavn').getValue();
    var mobile_number_value = Ext.getCmp('form_indsamler_mobiltelefon').getValue();
    var phone_number_value = Ext.getCmp('form_indsamler_fastnettelefon').getValue();
    var email_address_value = Ext.getCmp('form_indsamler_emailadresse').getValue();
    var address_value = Ext.getCmp('form_indsamler_adresse').getValue();
    var group_value = Ext.getCmp('form_indsamlere_group').getValue();
    var campaign_value = Ext.getCmp('form_indsamlere_campaign').getValue();
    var venue_value = Ext.getCmp('form_indsamlere_venue').getValue();

    
    Ext.Ajax.request({
	url: 'db_functions.php',
	method: 'post',
	params: {
	    function  : 'commit_collector',
	    edit: edit_value,
	    number: number_value,
	    uid: uid_value,
	    first_name: first_name_value,
	    last_name: last_name_value,
	    mobile_number: mobile_number_value,
	    phone_number: phone_number_value,
	    email_address: email_address_value,
	    address: address_value,
	    group_uid: group_value,
	    campaign_uid:  campaign_value,
	    venue_uid: venue_value
	},
	success: function(response, object) {
	    var res = Ext.decode(response.responseText);
	 
            if (res.success == false){
		Ext.MessageBox.alert("Fejl", res.msg);
	    } else {
		var selection = Ext.getCmp("indsamlere_grid").getSelectionModel().getSelection();
		
		if (selection.length != 0) {
		    selection[0].data = res.results[0]
		    var index = Ext.getCmp("indsamlere_grid").getStore().indexOf(selection[0]);
		    Ext.getCmp("indsamlere_grid").getView().refreshNode(index);
		}

		//Ext.MessageBox.alert("Info", res.msg);
	    }

	    if (edit_value == null || edit_value == '') {
		search("indsamlere");
	    }
	    search("grupper");
	   
	}
    });
}

function edit_indsamler(data) {
    showIndsamlerForm('Rediger indsamler', true, data);
}

var contextmenu_indsamlere = new Ext.menu.Menu({
    items: [
	{ 
	    text: 'Rediger',
	    icon: 'app/view/edit_row.gif',
	    handler: function() {
		var selection = Ext.getCmp("indsamlere_grid").getSelectionModel().getSelection();
		if (selection.length > 0) {
		    edit_indsamler(selection[0]);
		}
	    }
	}, { 
	    text: 'Slet',
	    icon: 'app/view/delete_row.gif',
	    handler: function() {
		var selection = Ext.getCmp("indsamlere_grid").getSelectionModel().getSelection();
		if (selection.length > 0) {
		    Ext.Msg.confirm('Spørgsmål', 'Er du sikker på, at du vil slette rækken?', function(btn, text){
			if (btn == 'yes'){
			    delete_row("indsamlere", "delete_collector", selection[0].get('uid'));
			    return;
			}
		    });
		}
	    }
	}
    ]
});

Ext.define('OpenDoors.view.IndsamlereView', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.indsamlerview',

    hideHeaders: true,
    

    items: [{
	xtype: 'component',
	html: '<font size="5">Indsamlere</font>',
 	margin: "30 0 0 30"
	
    }, {
	xtype: 'combobox',
	id: 'choose_venue_indsamlere_combobox',
	width: 250,
	margin: "50 0 0 30",
	displayField: 'name',
	valueField: 'uid',
	fieldLabel: "Vælg mødested",
	labelWidth: 100,
	store: 'ChooseVenueCombobox',
	emptyText: "Alle",
	queryParam: 'search_value',
	listeners:{  
	    scope:this,  
	    select: function(f,e) {  
		search("indsamlere");
	    }  
	}
    }, {
	xtype: 'container',
	width: 600,
	layout: 'hbox',
	border: false,
	items: [{
	    xtype: 'textfield',
	    id: 'search_indsamlere_field',
	    width: 300,
	    margin: "20 0 0 30",
	    listeners:{  
		scope:this,  
		specialkey: function(f,e) {  
		    if(e.getKey()==e.ENTER) {  
			search("indsamlere");
		    }  
		}  
	    }
	}, {
	    xtype: 'button',
	    width: 100,
	    text: 'Søg/Opdater',
	    id: 'search_indsamlere_button',
	    margin: "20 0 0 10"
	}, {
	    xtype: 'button',
	    width: 100,
	    text: 'Tilføj...',
	    id: 'add_indsamler_button',
	    margin: "20 0 0 10"
	}]
    }, {
	xtype: 'grid',
	id: 'indsamlere_grid',
	columnLines: true,
	margin: "30 15 30 15",
	store: 'Indsamlere',
	verticalScroller: {
	    xtype: 'paginggridscroller'
	},
	listeners: {
	    beforeitemcontextmenu: function(view, record, item, index, e)
	    {
		e.stopEvent();
		contextmenu_indsamlere.showAt(e.getXY());
	    }
	},
	
	columns: [{
	    xtype: 'rownumberer',
	    sortable: false,
	    width: 50
	}, {
	    text: 'Indsamlernr.',
	    dataIndex: 'number',
	    align:'right', 
	    style: 'text-align:left',
	    width: 90,
	    renderer: renderTip
	}, {
	    text: 'Fornavn',
	    dataIndex: 'first_name',
	    flex: 1,
	    renderer: renderTip
	}, {
	    text: 'Efternavn',
	    dataIndex: 'last_name',
	    flex: 1,
	    renderer: renderTip
	}, {
	    text: 'Adresse',
	    dataIndex: 'address',
	    flex: 1,
	    renderer: renderTip
	}, {
	    text: 'E-mail',
	    dataIndex: 'email_address',
	    flex: 1,
	    renderer: renderTip
	}, {
	    text: 'Mobilnr.',
	    dataIndex: 'mobile_number',
	    align:'right', 
	    style: 'text-align:left',
	    flex: 1,
	    renderer: renderTip
	}, {
	    text: 'Fastnettelefon',
	    dataIndex: 'phone_number',
	    align:'right', 
	    style: 'text-align:left',
	    flex: 1,
	    renderer: renderTip
	}, {
	    text: 'Indsamlingsgruppe',
	    dataIndex: 'group_name',
	    flex: 1,
	    renderer: renderTip
	}, {
	    text: 'Mødested',
	    dataIndex: 'venue_name',
	    flex: 1,
	    renderer: renderTip
	}]
    }],
    
    initComponent: function() {
        
        this.callParent();
    }
});

